package com.ruoyi.ora.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.enums.dict.AiModel;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.ora.domain.ChatRequest;
import com.ruoyi.ora.domain.ChatResponse;
import com.ruoyi.ora.service.IAiInterfaceService;
import com.ruoyi.system.service.ISysConfigService;
import org.springframework.stereotype.Service;

import javax.net.ssl.*;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.Map;


@Service
public class SGJChatServiceImpl implements IAiInterfaceService {

    private ISysConfigService configService = SpringUtils.getBean(ISysConfigService.class);

    @Override
    public String chatCompletions(String prompt) {
        //        冬季的一个晚上，窗外飘起了细腻的雪花。微弱的灯光透过窗帘洒在室内，给这寒冷的夜晚增添了一丝温暖。站在窗前，我静静地望着天空，心中涌起一阵宁静。给以上内容做一个10字左右的总结
        try {
            disableSSLVerification();
            String sgjAiConfig = configService.selectConfigByKey("ora_sgj_ai_config");
            if (StringUtils.isNotEmpty(sgjAiConfig)){
                JSONObject jsonObject = JSONObject.parseObject(sgjAiConfig);
//                String url = "https://ai.toasin.cn/web.php/chatApi/sendText";
//                String token = "U2FsdGVkX18b06al3Fefzwy0bDN6xQ4o4grqr1ryOLfgRnza1I0YkHHCRX4yuXceORK3o5c8JjI=";
//                String group_id = "41";
//                String ai = "openai3";

                String url = jsonObject.getString("url");
                String token = jsonObject.getString("token");
                String group_id = jsonObject.getString("group_id");
                String ai = jsonObject.getString("ai");


                return callApi(url, token, group_id, ai, prompt);
            }


        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public ChatResponse getChatCompletions(String prompt) {
        return null;
    }

    @Override
    public ChatResponse getChatCompletions(String prompt, AiModel aiModel) {
        return null;
    }

    @Override
    public ChatResponse chatCompletions(ChatRequest chatRequest) {
        return null;
    }

//    @Override
//    public ChatResponse getChatCompletionsTran(String json) {
//        return null;
//    }
//
//    @Override
//    public ChatResponse getChatCompletionsTran1(String json) {
//        return null;
//    }


    public static String toasinAi(String ai, String message, String cookie, String group_id){
        try {
            String url = "https://ai.toasin.cn/web.php/chat/sendText";

            // Prepare the payload
            Map<String, String> payload = new HashMap<>();
            payload.put("ai", ai);
            payload.put("group_id", group_id);
            payload.put("message", message);

//            String message = "冬季的一个晚上,窗外飘起了细腻的雪花。微弱的灯光透过窗帘酒在E室内,给这寒冷的夜晚增添了一丝温暖。站在窗前,我静静地望着天天空,心中涌起一阵宁静。给以上内容做一个10字左右的总结";

            // Prepare the request body
            StringBuilder postData = new StringBuilder();
            for (Map.Entry<String, String> param : payload.entrySet()) {
                if (postData.length() != 0) postData.append('&');
                postData.append(param.getKey());
                postData.append('=');
                postData.append(param.getValue());
            }
            byte[] postDataBytes = postData.toString().getBytes(StandardCharsets.UTF_8);

            // Create and configure the connection
            HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            conn.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
//            String cookie = "foxai_pc_sitecode=pk4h; PHPSESSID=6800b0029fb7b1521; foxai_pc_token=6800b0029fb7b1521";
            conn.setRequestProperty("Cookie", cookie);
            conn.setDoOutput(true);

            // Send the request
            try (DataOutputStream wr = new DataOutputStream(conn.getOutputStream())) {
                wr.write(postDataBytes);
            }

            // Read the response
            int responseCode = conn.getResponseCode();
//            System.out.println("Response Code: " + responseCode);

            StringBuilder response;
            try (BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()))) {
                String inputLine;
                response = new StringBuilder();
                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
            }

            return response.toString().trim();

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    // 主调用方法
    public static String callApi(String url, String token, String groupId, String ai, String message) throws Exception {
        try {
            // Prepare the payload
            Map<String, String> payload = new HashMap<>();
            payload.put("ai", ai);
            payload.put("group_id", groupId);
            payload.put("message", message);

            // Prepare the request body
            StringBuilder postData = new StringBuilder();
            for (Map.Entry<String, String> param : payload.entrySet()) {
                if (postData.length() != 0) postData.append('&');
                postData.append(param.getKey());
                postData.append('=');
                postData.append(param.getValue());
            }
            byte[] postDataBytes = postData.toString().getBytes(StandardCharsets.UTF_8);

            // Create and configure the connection
            HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            conn.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
            conn.setRequestProperty("x-token", token);
            conn.setDoOutput(true);

            // Send the request
            try (DataOutputStream wr = new DataOutputStream(conn.getOutputStream())) {
                wr.write(postDataBytes);
            }

            // Read the response
            int responseCode = conn.getResponseCode();
//            System.out.println("Response Code: " + responseCode);

            StringBuilder response;
            try (BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()))) {
                String inputLine;
                response = new StringBuilder();
                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
            }

            return response.toString().trim();

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    // 构建请求体JSON
    private static String buildRequestBody(String groupId, String ai, String message) {
        Map<String, String> requestBody = new HashMap<>();
        requestBody.put("group_id", groupId);
        requestBody.put("ai", ai);
        requestBody.put("message", message);
        // 使用简单的JSON构建方式，实际项目中建议使用Jackson/Gson
        return "{\"group_id\":\"" + groupId + "\",\"ai\":\"" + ai + "\"}";
    }

    // 可选：跳过SSL验证（仅用于测试环境）
    public static void disableSSLVerification() {
        try {
            // 创建信任所有证书的TrustManager
            TrustManager[] trustAllCerts = new TrustManager[]{
                    new X509TrustManager() {
                        public X509Certificate[] getAcceptedIssuers() {
                            return null;
                        }
                        public void checkClientTrusted(X509Certificate[] certs, String authType) {
                        }
                        public void checkServerTrusted(X509Certificate[] certs, String authType) {
                        }
                    }
            };

            // 安装信任管理器
            SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null, trustAllCerts, new java.security.SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

            // 安装所有主机名验证器
            HostnameVerifier allHostsValid = (hostname, session) -> true;
            HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 使用示例
    public static void main(String[] args) {
        try {
            // 如果是HTTPS且证书不受信任，可以临时跳过验证（仅测试环境使用）
             disableSSLVerification();

            String url = "https://ai.toasin.cn/web.php/chatApi/sendText";
            String token = "U2FsdGVkX18b06al3Fefzwy0bDN6xQ4o4grqr1ryOLfgRnza1I0YkHHCRX4yuXceORK3o5c8JjI=";
            String groupId = "41";
            String ai = "openai3";
            String message = "冬季的一个晚上，窗外飘起了细腻的雪花。微弱的灯光透过窗帘洒在室内，给这寒冷的夜晚增添了一丝温暖。站在窗前，我静静地望着天空，心中涌起一阵宁静。给以上内容做一个10字左右的总结";

            String response = callApi(url, token, groupId, ai, message);
            System.out.println("API响应: " + response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
